package sf.dsl.example;


import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLParameter;
import sf.database.meta.ColumnMapping;
import sf.spring.util.CollectionUtils;
import sf.tools.ArrayUtils;
import sf.tools.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 自定义字符串列，用于扩展
 */
public class StringCondition implements ICondition {

    protected String sqlContent;
    /**
     * 值,可为Collection子类或任意类型
     */
    protected Object value;
    protected ValueType valueType;

    /**
     * 该字段非必要
     */
    protected ColumnMapping columnMapping;

    public StringCondition(String content) {
        this.sqlContent = content;
        this.valueType = ValueType.noValue;
    }

    public StringCondition(String content, Object value) {
        this.sqlContent = content;
        this.value = value;
        this.valueType = ValueType.singleValue;
    }

    public StringCondition(String condition, Collection<?> collection) {
        this.sqlContent = condition;
        if (CollectionUtils.isNotEmpty(collection)) {
            value = collection;
            this.valueType = ValueType.listValue;
        } else {
            this.valueType = ValueType.noValue;
        }
    }

    public StringCondition(String condition, Object... array) {
        this.sqlContent = condition;
        if (ArrayUtils.isNotEmpty(array)) {
            value = array;
            this.valueType = ValueType.arrayValue;
        } else {
            this.valueType = ValueType.noValue;
        }
    }

    @Override
    public void toSql(StringBuilder sb, List<SQLParameter> list, AtomicBoolean mustTableAlias, DBDialect dialect) {
        if (StringUtils.isNotBlank(sqlContent)) {
            sb.append(sqlContent);
        }
        ColumnMapping[] columnMappings = null;
        if (columnMapping != null) {
            columnMappings = new ColumnMapping[]{columnMapping};
        }
        DSLMethod.setSqlParameters(list, 1, columnMappings, null, value, valueType);
    }

    public ColumnMapping getColumnMapping() {
        return columnMapping;
    }

    public void setColumnMapping(ColumnMapping columnMapping) {
        this.columnMapping = columnMapping;
    }
}
